package com.woohua.thread.lockreadwrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/***
 * @title Cache
 * @description
 * @author woo hua
 * @version 1.0.0
 * @create 2023/3/16 14:31
 **/
public abstract class Cache<K, V> {

    final Map<K, V> m = new HashMap<K, V>();

    final ReadWriteLock rwl = new ReentrantReadWriteLock();
    final Lock r = rwl.readLock();
    final Lock w = rwl.writeLock();

    public V get(K key) {
        r.lock();
        try {
            return m.get(key);
        } finally {
            r.unlock();
        }
    }

    public V put(K key, V value) {
        w.lock();
        try {
            return m.put(key, value);
        } finally {
            w.lock();
        }
    }

    public V remove(K key) {
        w.lock();
        try {
            return m.remove(key);
        } finally {
            w.unlock();
        }
    }

    void _init() {
        w.lock();
        try {
            init();
        } finally {
            w.unlock();
        }
    }

    /**
     * 缓存初始化，子类实现
     */
    protected abstract void init();
}
